package router

import (
	"github.com/bgmp/handler"
	"github.com/bgmp/handler/algorithm"
	"github.com/bgmp/handler/auth"
	"github.com/bgmp/handler/diet"
	"github.com/bgmp/handler/doctor"
	"github.com/bgmp/handler/file"
	"github.com/bgmp/handler/insulin"
	"github.com/bgmp/handler/ping"
	"github.com/bgmp/handler/sport"
	"github.com/bgmp/handler/user"
	"github.com/bgmp/handler/user_detail"
	"github.com/bgmp/middleware"
	"github.com/gin-contrib/gzip"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"net/http"
)

// Load loads the middlewares, routes, handlers.
func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine {
	// Middlewares.
	g.Use(gin.Recovery())
	g.Use(mw...)
	g.Use(gzip.Gzip(gzip.DefaultCompression))

	// 404 Handler.
	g.NoRoute(func(c *gin.Context) {
		handler.ReplyString(c, http.StatusNotFound, "The incorrect API route.")
	})

	u := g.Group(viper.GetString("apibase"))
	u.Use(middleware.Logging)
	{
		u.Any("/ping", ping.DefaultHandler)
		u.Any("/auth", auth.DefaultHandler)

		api := u.Group("/api")
		api.Use(middleware.JWT)
		{
			api.Any("/user", user.DefaultHandler)
			api.Any("/user_detail", user_detail.DefaultHandler)
			api.Any("/diet", diet.DefaultHandler)
			api.Any("/algorithm", algorithm.DefaultHandler)
			api.Any("/sport", sport.DefaultHandler)
			api.Any("/insulin", middleware.DoctorAuth, insulin.DefaultHandler)
			api.Any("/doctor", middleware.DoctorAuth, doctor.DefaultHandler)
		}
	}

	f := g.Group(viper.GetString("apibase") + "/api/files")
	f.Use(middleware.NonJsonLogging)
	f.POST("/upload", middleware.JWT, file.UploadFile)
	f.GET("/download", file.DownloadFile)

	return g
}
